<template>
  <div class="index-header">
    <!-- 顶部 Nav -->
    <top-nav></top-nav>

    <div class="header-content">
      <div class="header-inner">
        <div class="inner-left">
          <div class="logo-left"></div>
          <div class="logo-right"></div>
        </div>
        <div class="inner-right">
          <div class="inner-right-top">
            <el-autocomplete
              class="inputSearch"
              size="small"
              clearable
              v-model="hospitalName.hospitalName"
              placeholder="请输入搜索值"
              label-name="标题名称"
              :trigger-on-focus="false"
              :fetch-suggestions="querySearch"
              @select="handleSelect"
            >
              <!-- <el-input placeholder="请输入内容" class="input-with-select" size="small" v-model="searchKey"> -->
              <el-button
                style="background-color:#409EFF;color:#fff;border-color: #409EFF;"
                slot="append"
                icon="el-icon-search"
                size="small"
                @click="setSearchKey()"
              ></el-button>
            </el-autocomplete>
            <!-- </el-input> -->
          </div>
          <div class="inner-right-bottom">
            <span v-for="item in shopCateList.slice(0, 7)"
              :key="item.id"  @click="changeCate(item)" class="cateli">
                {{item.name}}
                <el-divider direction="vertical"></el-divider>
            </span>
            
            <!-- <span>苹果</span>
            <el-divider direction="vertical"></el-divider>
            <span>三星</span>
            <el-divider direction="vertical"></el-divider>
            <span>小米</span>
            <el-divider direction="vertical"></el-divider>
            <span>OPPO</span>
            <el-divider direction="vertical"></el-divider>
            <span>VIVO</span> -->
          </div>
        </div>
        <div style="padding-left: 60px;">
          <el-button type="warning" size="small" icon="el-icon-goods" @click="toCart()">购物车</el-button>
        </div>
      </div>
    </div>

    <!-- 导航部分 -->
    <div :class="['header-menu', isFixed? 'yesFixed': 'noFixed']">
      <ul class="menu">
        <li class="active" @mousemove="activemove" @mouseleave="activeleave">
          <div>
            <i class="el-icon-s-operation"></i>
            <a href="#/shopList">商品分类</a>
          </div>
          <ul class="categoryul">
            <li @click="changeCate('')">全部</li>
            <li
              v-for="(item) in shopCateList"
              :key="item.id"
              @click="changeCate(item)"
            >{{item.name}}</li>
          </ul>
        </li>
        <li>
          <a href="#/index">首页</a>
        </li>
        <li>
          <a href="#">最后疯抢</a>
        </li>
        <li>
          <a href="#">品牌清仓</a>
        </li>
        <li>
          <a href="#">特价</a>
        </li>
        <li style="float:right;">
          <el-dropdown>
            <a href="#">
              更多
              <i class="el-icon-arrow-down el-icon--right"></i>
            </a>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>唯品会</el-dropdown-item>
              <el-dropdown-item>京东</el-dropdown-item>
              <el-dropdown-item>淘宝</el-dropdown-item>
              <el-dropdown-item>小米商城</el-dropdown-item>
              <el-dropdown-item>华为官网</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import TopNav from "../Show/TopNav";
import {mapState} from 'vuex'

export default {
  components: {
    TopNav,
  },
  computed:{
    ...mapState({
      shopCateList: state => state.cate.shopCateList
    })
  },
  data() {
    return {
      isFixed: false,
      // // 商品分类列表
      // shopCateList: [],
      // // 搜索关键字
      // searchKey: '',
      // 获取商品列表请求参数
      shopListQuery:{
          pageNum: 1,
          pageSize: 10
      },
      getHospitalData: [], // 根据输入值  查询到的结果
      hospitalName: { hospitalName: "", keyID: "" }, // 输入框绑定的数据
      remindData: [], // 存放提醒框的数据
    };
  },

  methods: {
    toCart() {
      this.$router.push("/shopCart");
    },
    changeFixed() {
      const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 130) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    },
    activemove() {
      const activeList = document.getElementsByClassName("categoryul");
      //  console.log(activeList[0].children);
      activeList[0].children.forEach((item) => {
        item.style.display = "inline";
      });
      //   activeList[0].style.transition = "all .3s";
      activeList[0].style.height = "300px";
      activeList[0].style.overflowY = "scroll";
      activeList[0].style.overflowX = "hidden";
    },
    activeleave() {
      const activeList = document.getElementsByClassName("categoryul");
      // activeList[0].style.transition = "all .3s";
      activeList[0].style.height = 0 + "px";
      setTimeout(() => {
        activeList[0].children.forEach((item) => {
          item.style.display = "none";
        });
      }, 300);
    },
    // 获取商品分类列表
    async getShopCateList() {
      const { data: res } = await this.$http.get("/category/select");
      console.log('商品分类列表', res)
      if (res.code == 200) {
        // this.shopCateList = res.data;
        this.$store.commit('setShopCateList', res.data)
      }
    },
    // 判断是否是shopList页
    judgePath() {
      var path = location.hash.substr(2);
      // console.log(path)
      if (path === "shopList") {
        return;
      } else {
        this.$router.push("/shopList");
      }
    },
    // 选择分类存储到cate
    changeCate(item) {
      this.$store.commit("setCate", item);
      this.judgePath();
    },
    
    // 删除str中所有a-b的内容（包含a和b）
    getNewStr(str, a, b){
      var start = str.indexOf(a)
      var end = str.indexOf(b)

      var newStr = str
      while(start !== -1 || end !== -1){
        // console.log('start:',start,'end:',end)
        var delStr = newStr.substr(start, end-start+1)
        newStr = newStr.replace(delStr, '')
        start = newStr.indexOf(a)
        end = newStr.indexOf(b)
        // console.log(num + ':' + newStr+'\n')
      }
        return newStr
    },
    // 搜索提示且搜索
    async querySearch(queryString, cb) {
      if (this.hospitalName.hospitalName !== "") {
        this.remindData = [];
        let searchMap = {
          name: "",
          category_id: "",
          price: "",
        };
        searchMap["name"] = this.hospitalName.hospitalName;
        const { data: res } = await this.$http.post(
          `/product/solrSearch?pageNum=${this.shopListQuery.pageNum}&pageSize=${this.shopListQuery.pageSize}`,
          searchMap
        );
        console.log("搜索提示", res);
        if (res.code == 200) {
          this.getHospitalData = res.data.list;
          this.getHospitalData.forEach((item) => {
            let obj = { value: '', keyId: ''}
            
            // 自定义处理获取字符串
            var stra = this.getNewStr(item.name, '<', '>')
            var strb = this.getNewStr(stra, '【', '】')
            // var strArr = strb.split(' ')

            obj.value = strb
            this.remindData.push(obj)
          })
          let nameTipsArray = this.remindData
          cb(nameTipsArray)
        }
      }
    },
    // 处理选中搜索关键字
    handleSelect(val){
      // console.log('选中-----')
      // console.log(val)
      this.$store.commit('setSearchKey', val)
      this.judgePath()
    },
    // 提交搜索关键字
    setSearchKey(){
      let obj = { value: '', keyId: ''}
      obj.value = this.hospitalName.hospitalName
      console.log('提交关键字：', obj.value)
      this.$store.commit('setSearchKey', obj)
      this.judgePath()
    },

    
  },
  mounted() {
    window.addEventListener("scroll", this.changeFixed);
  },
  destroyed() {
    window.removeEventListener("scroll", this.changeFixed);
  },
  created() {
    if(this.shopCateList.length !== 0){
        // console.log('shopCateList在vuex中存在')
        return
    }else{
        this.getShopCateList()
    }

  },
};
</script>

<style lang="less" scoped>
.el-button:focus {
  outline: none;
}
.yesFixed {
  box-shadow: 0px 5px 14px -8px #5e5e5e;
  position: fixed;
  top: 0;
}
.noFixed {
  box-shadow: 0px 5px 14px -10px #5e5e5e;
  position: absolute;
  bottom: 0;
}
.index-header {
  height: 165px;
  // margin-bottom: 20px;
  // box-shadow: 0px 5px 14px -11px #5E5E5E;
  position: relative;
  .header-content {
    width: 1200px;
    height: inherit;
    margin: 0 auto;
    position: relative;
    // border: 1px solid red;
    .header-inner {
      height: 55%;
      display: flex;
      // justify-content: space-between;
      align-items: center;
      .inner-left {
        width: 40%;
        display: flex;
        justify-content: space-between;
        .logo-left {
          background-image: url(../../assets/images/logo/logo.png);
          background-size: cover; /* 将背景图片等比缩放填满整个容器 */
          height: 75px;
          width: 150px;
        }
        .logo-right {
          background-image: url(../../assets/images/logo/logo2.png);
          background-size: cover; /* 将背景图片等比缩放填满整个容器 */
          height: 85px;
          width: 280px;
        }
        // border: 1px solid yellow;
      }
      .inner-right {
        width: 50%;
        height: 100%;
        // border: 1px solid black;
        display: flex;
        flex-direction: column;
        // justify-content: center;
        // align-items: center;
        padding: 28px 10px 0 100px;
        .inner-right-top {
          .inputSearch {
            width: 100%;
          }
        }
        .inner-right-bottom {
          margin-top: 5px;
          padding-left: 5px;
          font-size: 11px;
          color: #999;
          .cateli{
            cursor: pointer;
          }
          .cateli:hover{
            color: #409EFF;
          }
        }
      }
    }
  }

  // 头部导航样式
  .header-menu {
    // border: 1px solid green;
    // position: absolute;
    // bottom: 0;
    // // position: fixed;
    // // top: 0;

    width: 100%;
    z-index: 10;
    background-color: #fff;
    padding: 0 160px;
    .menu {
      width: 1200px;
    }
    ul {
      font-size: 14px;
      font-family: Arial, Helvetica, sans-serif;
      list-style: none;
      padding: 0;
      li {
        float: left;
        min-width: 80px;
        text-align: center;
        transition: all 0.5s;
        a {
          text-decoration: none;
          color: #333;
          display: inline-block;
          padding: 0.5rem 0;
        }
        a:hover {
          color: #409eff;
        }
      }
    }
    .active {
      min-width: 140px;
      background: #409eff;
      a {
        color: #fff;
      }
      a:hover {
        color: #fff;
      }
      i {
        color: #fff;
      }
      position: relative;
      ul {
        // height: 0px;
        // width: 140px;
        // overflow: hidden;
        z-index: 9;
        position: absolute;
        color: #fff;
        transition: all 0.3s;
        background: #409eff;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        li {
          display: none;
          float: left;
          padding: 0.5rem 0px;
          cursor: pointer;
          min-width: 130px;
        }
        li:hover {
          color: #409eff;
          font-weight: bold;
          background: #fff;
          margin: 5px;
          border-radius: 5px;
          box-shadow: 0 3px 12px 0 rgba(0, 0, 0, 0.1) inset;
        }
      }
      ul::-webkit-scrollbar {
        display: none; /* Chrome Safari */
      }

      ul {
        scrollbar-width: none; /* firefox */
        -ms-overflow-style: none; /* IE 10+ */
        overflow-x: hidden;
        overflow-y: auto;
      }
    }
    // .active:hover {
    //   ul {
    //     height: 200px;
    //     li {
    //       display: inline;
    //     }
    //   }
    // }
  }
}
</style>